<template>
  <el-drawer
    ref="drawerRef"
    :title="courseId ? '编辑常规课' : '新增常规课'"
    :visible.sync="isShowDrawer"
    :before-close="closeDrawer"
    size="1000px"
  >
    <el-form
      ref="ruleForm"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="120px"
      label-suffix="："
    >
      <div class="property-title">课程信息</div>
      <el-form-item label="课程图片" prop="configPicture">
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            use-type="COURSE_IMG"
            :fixed-number="[690, 388]"
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
        <el-upload
          class="device-uploader"
          :action="uploadFileUrl"
          :data="uploadData"
          :auto-upload="false"
          :show-file-list="false"
          accept=".jpg,.png"
          :on-change="addFileChange"
        >
          <i class="el-icon-plus uploader-icon" />
          <div
            v-show="param.configPicture"
            class="file"
            :style="'background-image: url(' + param.configPicture + ')'"
          >
            <div class="delete">
              <i
                class="el-icon-delete icon"
                @click.stop="deleteDeviceConfigAddImage"
              />
            </div>
          </div>
        </el-upload>
        <div style="display: inline-block">建议图片尺寸690px X 388px</div>
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="param.courseName"
          type="text"
          :disabled="status == '4' || status == '3'"
          class="w400"
          placeholder="请输入课程名称"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="课程类型" prop="courseType">
        <el-select v-model="param.courseType" :disabled="courseId != '' && status != '1'" placeholder="请选择课程类型" class="w400" @change="courseTypeChange">
          <el-option
            v-for="item in lxList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="课程人数" prop="rs"> -->
      <el-form-item label="课程人数" :prop="param.numLimit == '2' ? 'rs' : 'aaaa'">
        <div class="df_ac" style="height: 36px;">
          <el-radio v-if="param.courseType != '1'" v-model="param.numLimit" :disabled="status == '4' || status == '3'" label="1">不限</el-radio>
          <el-radio v-model="param.numLimit" :disabled="status == '4' || status == '3'" label="2">指定人数</el-radio>
          <div v-if="param.numLimit === '2'" class="df">
            <el-input
              v-model="param.rs[0]"
              type="number"
              class="w200"
              oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
              placeholder="人数下限 >=1"
              @blur="check_num(0)"
            />
            <span class="ml10 mr10">-</span>
            <el-input
              v-model="param.rs[1]"
              type="number"
              oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
              class="w200"
              placeholder="人数上限"
              @blur="check_num(1)"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="授课教练" prop="teacherId">
        <el-select v-model="param.teacherId" placeholder="请选择授课教练" class="w400">
          <el-option
            v-for="item in jlList"
            :key="item.teacherId"
            :label="item.teacherName"
            :value="item.teacherId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课时数" prop="classNum">
        <el-input v-model="param.classNum" :disabled="status == '4' || status == '3'" oninput="value=value.replace(/^(0+)|[^\d]+/g, '').slice(0, 5)" placeholder="请输入课时数" class="w400" />
      </el-form-item>
      <el-form-item label="上课地点" prop="site">
        <el-input
          v-model="param.site"
          type="text"
          class="w400"
          placeholder="请输入上课地点"
          maxlength="20"
        />
      </el-form-item>
      <template v-if="param.courseType != 3">
        <el-form-item label="开课日期" prop="beginDate" :rules="{ required: param.courseType == 3 ? false:true, message: '请选择开课日期', trigger: 'change' }">
          <el-date-picker
            v-model="param.beginDate"
            :picker-options="pickerOptions"
            type="date"
            class="w400"
            :disabled="status == '4'"
            value-format="yyyy-MM-dd"
            placeholder="请选择开课日期"
            @change="beginDateChange"
          />
        </el-form-item>
        <el-form-item label="结课日期" prop="courseEndDate" :rules="{ required: param.courseType == 3 ? false:true, message: '请选择结课日期', trigger: 'change' }">
          <el-date-picker
            v-model="param.courseEndDate"
            :picker-options="pickerOptions"
            type="date"
            class="w400"
            value-format="yyyy-MM-dd"
            placeholder="请选择结课日期"
            @change="courseEndDateChange"
          />
        </el-form-item>
        <el-form-item label="报名截止日期" prop="endTime" :rules="{ required: param.courseType == 3 ? false:true, message: '请选择报名截止日期', trigger: 'change' }">
          <el-date-picker
            v-model="param.endTime"
            :picker-options="pickerOptions"
            type="datetime"
            class="w400"
            :disabled="status == '4' || status == '3'"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择报名截止日期"
            @change="endTimeChange"
          />
        </el-form-item>
      </template>
      <el-form-item label="课程简介" prop="introduction">
        <el-input
          v-model="param.introduction"
          type="text"
          class="w400"
          placeholder="请输入课程简介"
          maxlength="100"
        />
      </el-form-item>
      <el-form-item label="课程详情" prop="des">
        <div class="secondColor">注：图片不支持复制粘贴，仅支持本地上传；</div>
        <quill-editor ref="myTextEditor" v-model="param.des" placeholder="请输入课程详情" class="myQuillEditor" :options="quillOption" />
      </el-form-item>

      <div class="property-title">售卖信息</div>
      <el-form-item label="课程总价" prop="price">
        <el-input
          v-model="param.price"
          type="text"
          class="w400"
          :disabled="courseId != '' && status != '1'"
          placeholder="请输入课程总价"
          oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
          maxlength="100"
        />
      </el-form-item>
      <el-form-item label="售卖方式" prop="channel">
        <el-checkbox-group v-model="param.channel" :disabled="status == '4' || status == '3'">
          <el-checkbox label="01">小程序端</el-checkbox>
          <el-checkbox label="02">场馆PC端</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <div class="property-title">其他信息</div>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="param.phone" class="w400" oninput="value=value.replace(/^(0+)|[^\d]+/g, '').slice(0, 16)" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="排序码">
        <el-input v-model="param.sortNum" maxlength="11" class="w400" oninput="value=value.replace(/^(0+)|[^\d]+/g, '').slice(0, 16)" placeholder="请输入排序码" />
      </el-form-item>
      <el-form-item label="是否热门课程" prop="isHot">
        <el-switch
          v-model="param.isHot"
          :active-value="'1'"
          :inactive-value="'0'"
        />
      </el-form-item>
      <el-form-item label="缺课是否补课">
        <el-radio v-model="param.muml" :disabled="status == '4' || status == '3'" label="1">是</el-radio>
        <el-radio v-model="param.muml" :disabled="status == '4' || status == '3'" label="0">否</el-radio>
      </el-form-item>
      <div class="line-style" />
      <div class="property-title">会员折扣</div>
      <el-form-item label="折扣类型" prop="discountType">
        <el-select v-model="param.discountType" :disabled="courseId != '' && status != '1'" placeholder="请选择折扣类型" class="w400">
          <el-option
            v-for="item in zkList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <div v-if="param.discountType == '1'" style="display: flex; flex-wrap: wrap">
        <el-form-item
          v-for="vip in vipType"
          :key="vip.id"
          align="center"
          :label="vip.cardName"
          style="width: 50%"
          :prop="`discountMap.${vip.id}`"
          :rules="{ required: true, message: '请输入会员折扣', trigger: 'blur' }"
        >
          <el-input
            v-model="param.discountMap[vip.id]"
            onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            oninput="if(value<0||value>1) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
            type="text"
            placeholder="请输入会员折扣(保留两位小数)"
            maxlength="20"
          />
        </el-form-item>
      </div>
      <el-form-item>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="onSubmit()"
        >提交</el-button>
        <el-button
          v-preventReClick
          @click="cancelSub"
        >取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script>
import { uploadFile, cardList, teacherList, editCourse, startCourse, infoCourse } from '@/api'
import { quillEditor } from 'vue-quill-editor'
import quillConfig from '@/api/sc.js'
import Cropper from '@/components/cropper'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  components: {
    quillEditor,
    Cropper
  },
  data() {
    var newRule = (rule, value, callback) => {
      if (value[0] === undefined && value[1] === undefined) {
        callback(new Error(rule.message || '请输入课程人数范围'))
      } else if (!/^\+?[1-9][0-9]*$/.test(value[0]) || !/^\+?[1-9][0-9]*$/.test(value[1])) {
        callback(new Error(rule.message || '请输入正确人数'))
      } else if (value[0] < 1) {
        callback(new Error(rule.message || '请输入正确人数范围'))
      } else if (Number(value[0]) > Number(value[1])) {
        callback(new Error(rule.message || '请输入正确人数范围'))
      } else {
        callback()
      }
    }
    return {
      isShowDrawer: false,
      courseId: '',
      status: '',
      param: {
        numLimit: '1',
        muml: '1',
        venueId: sessionStorage.getItem('venueId'),
        termType: '0',
        channel: [],
        rs: [],
        xqList: [],
        discountMap: {}
      },

      subLoading: false,
      dialogCropperVisible: false,
      optionImg: '',
      files: {},
      fileinfo: {},
      uploadFileUrl: uploadFile,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
        }
      },
      uploadData: {
        folder: 'COURSE_IMG',
        type: ''
      },
      lxList: [
        { value: '1', label: '团体课' },
        // { value: '2', label: '私教课 ' },
        { value: '3', label: '长期课' }
      ],
      termTypeList: [
        { value: '0', label: '年' },
        { value: '1', label: '月 ' },
        { value: '2', label: '日' }
      ],
      lmList: [
        { value: '01', label: '足球' },
        { value: '02', label: '篮球' },
        { value: '03', label: '羽毛球' }
      ],
      payStatusList: [
        { value: '0', label: '未支付' },
        { value: '1', label: '过期未付' },
        { value: '2', label: '已取消' },
        { value: '3', label: '已支付' }
      ],
      zkList: [
        { value: '0', label: '默认折扣' },
        { value: '1', label: '自定义折扣' }
      ],
      jlList: [],
      vipType: [],
      venueId: sessionStorage.getItem('venueId'),
      rules: {
        configPicture: [{ required: true, message: '请上传课程图片', trigger: 'change' }],
        courseName: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
        courseType: [{ required: true, message: '请选择课程类型', trigger: 'change' }],
        teacherId: [{ required: true, message: '请选择授课教练', trigger: 'change' }],
        itemsIds: [{ required: true, message: '请选择课程类目', trigger: 'change' }],
        price: [{ pattern: /^(([0-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, required: true, message: '请输入正确课时总价(元),最多保留2位小数', trigger: 'blur' }],
        classNum: [{ pattern: /^\+?[1-9][0-9]*$/, required: true, message: '请输入正确课时数', trigger: 'blur' }],
        rs: [{ required: true, validator: newRule, trigger: 'change' }],
        site: [{ required: true, message: '请输入上课地点', trigger: 'blur' }],
        introduction: [{ required: true, message: '请输入课程简介', trigger: 'blur' }],
        des: [{ required: true, message: '请输入课程详情', trigger: 'blur' }],
        xqList: [{ required: true, message: '请上传详情图片', trigger: 'change' }],
        discountType: [{ required: true, message: '请选择折扣类型', trigger: 'change' }],
        channel: [{ type: 'array', required: true, message: '请至少选择一个售卖方式', trigger: 'change' }]
      },
      content: '',
      quillOption: quillConfig
    }
  },
  created() {
    this.getTeachList()
  },
  methods: {
    getDetail(courseId) {
      // 获取卡类型列表
      infoCourse({ param: { courseId }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          const obj = res.record
          if (obj.channel) {
            obj.channel = obj.channel.split(',')
          } else {
            obj.channel = []
          }
          this.param = {
            ...obj,
            termType: obj.termType ?? '0',
            flag: '2',
            itemsIds: obj.courseItemIds,
            beginDate: obj.beginDate ?? '',
            configPicture: obj.courseImageUrl,
            rs: [obj.peopleNumLow, obj.peopleNumUp]
          }
          if (res.record.discountType === '0') {
            this.$set(this.param, 'discountMap', {})
            this.getCardList()
          } else {
            const discountMap = obj.discountMap
            this.$set(this.param, 'discountMap', obj.discountMap)
            const arrs = []
            cardList({})
              .then((res) => {
                if (res.errorCode === '000000') {
                  const vip = res.recordList
                  vip.forEach(e => {
                    if (Object.prototype.hasOwnProperty.call(discountMap, e.id)) {
                      arrs.push(e)
                    }
                  })
                  this.vipType = arrs
                }
              })
              .catch((err) => {
                console.log(err)
              })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    courseTypeChange(val) {
      if (val === '1') {
        this.param.numLimit = '2'
      }
    },
    closeDrawer() {
      this.isShowDrawer = false
      this.$emit('close')
    },
    endTimeChange(val) {
      if (val > this.param.courseEndDate) {
        this.param.endTime = ''
        this.$message.warning('报名截止时间应小于结束时间')
      }
    },
    courseEndDateChange(val) {
      if (val < this.param.beginDate) {
        this.param.courseEndDate = ''
        this.$message.warning('结束时间应大于开始时间')
        return
      }
      if (val < this.param.endTime) {
        this.param.courseEndDate = ''
        this.$message.warning('报名截止时间应小于结束时间')
      }
    },
    beginDateChange(val) {
      if (val > this.param.courseEndDate) {
        this.param.beginDate = ''
        this.$message.warning('结束时间应大于开始时间')
      }
    },
    check_num(e) {
      this.param.rs[e] = this.param.rs[e].replace(/[^\d]/g, '')
    },
    getTeachList(page) {
      const venueId = sessionStorage.getItem('venueId')
      teacherList({ param: { venueId, teacherType: '0', status: '1', isOnJob: '1' }})
        .then(res => {
          this.jlList = res.recordList
        })
    },
    getCardList() {
      // 获取卡类型列表
      cardList({})
        .then((res) => {
          if (res.errorCode === '000000') {
            this.vipType = res.recordList
            const vip = res.recordList
            vip.forEach(e => {
              this.$set(this.param.discountMap, e.id, '')
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 上传图片成功
    uploadSuccess(res, file, fileList) {
      if (res.success) {
        this.$set(this.param, 'configPicture', res.showUrl)
        this.$set(this.param, 'courseImage', res.insertUrl)
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    // 上传图片，开始裁剪
    async addFileChange(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'configPicture', config.showUrl)
        this.$set(this.param, 'courseImage', config.insertUrl)
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || '上传失败')
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    uploadSuccesss(res, file, fileList) {
      if (res.success) {
        const arr = this.param.xqList
        res.url = res.showUrl
        arr.push(res)
        this.$set(this.param, 'xqList', arr)
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    // 删除已上传图片
    deleteDeviceConfigAddImage() {
      this.$set(this.param, 'courseImage', '')
      this.$set(this.param, 'configPicture', '')
    },
    handleRemove(file, fileList) {
      this.$set(this.param, 'xqList', fileList)
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // const arr = this.param.xqList
          // let str = ''
          // arr.forEach(e => {
          //   str = str + e.insertUrl + ','
          // })
          this.param.price = Number(this.param.price)
          this.param.venueId = this.venueId
          const param = { ...this.param }
          param.classNum = Number(param.classNum)
          param.channel = param.channel.join(',')
          param.flag = '2'
          this.subLoading = true
          if (param.numLimit === '1') {
            param.numLow = null
            param.numUp = null
            param.peopleNumLow = null
            param.peopleNumUp = null
          } else {
            param.numLow = Number(this.param.rs[0])
            param.numUp = Number(this.param.rs[1])
            param.peopleNumLow = Number(this.param.rs[0])
            param.peopleNumUp = Number(this.param.rs[1])
          }
          if (this.courseId) {
            editCourse({
              param
            })
              .then(res => {
                this.subLoading = false
                if (res.errorCode === '000000') {
                  this.$message.success('提交成功')
                  this.isShowDrawer = false
                  this.$emit('success')
                  this.$emit('close')
                }
              })
              .catch(err => {
                this.subLoading = false
                console.log(err)
              })
          } else {
            startCourse({
              param
            })
              .then(res => {
                this.subLoading = false
                if (res.errorCode === '000000') {
                  this.$message.success('提交成功')
                  this.isShowDrawer = false
                  this.$emit('success')
                  this.$emit('close')
                }
              })
              .catch(err => {
                this.subLoading = false
                console.log(err)
              })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancelSub() {
      this.isShowDrawer = false
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.line-style {
  margin-bottom: 20px;
}
.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}
</style>
